package com.java.simple.study.juc.p2;

import com.java.simple.study.tool.Sleeper;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhoujunlin
 * @date 2022年04月05日 16:40
 * @desc
 */
@Slf4j(topic = "c.TestJoin")
public class TestJoin {

    private static int r = 0;
    private static int r1 = 0;
    private static int r2 = 0;

    public static void main(String[] args) throws InterruptedException {
//        test1();
//        test2();
        test3();
    }

    private static void test1() throws InterruptedException {
        log.debug("开始");
        Thread t1 = new Thread(() -> {
            log.debug("开始");
            Sleeper.sleep(1);
            log.debug("结束");
            r = 10;
        });
        t1.start();
        // 阻塞等待线程执行完毕
        t1.join();
        // 10
        log.debug("结果为：{}", r);
        log.debug("结束");
    }

    private static void test2() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            Sleeper.sleep(1);
            r1 = 10;
        });
        Thread t2 = new Thread(() -> {
            Sleeper.sleep(2);
            r2 = 20;
        });
        t1.start();
        t2.start();
        long start = System.currentTimeMillis();
        log.debug("join begin");
        t2.join();
        log.debug("t2 join end");
        // t2执行完时  t1也一定执行完了
        t1.join();
        log.debug("t1 join end");
        long end = System.currentTimeMillis();
        log.debug("r1：{}, r2:{}, cost:{}", r1, r2, end - start);
    }

    private static void test3() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            Sleeper.sleep(2);
            r1 = 10;
        });
        long start = System.currentTimeMillis();
        t1.start();
        log.debug("join begin");
        // t1执行完 join便不会一直阻塞等待
        t1.join(3000);
        long end = System.currentTimeMillis();
        log.debug("r1:{}, cost:{}", r1, end - start);
    }

}
